import api from '@api/store_api';
import { toast, log, err, to } from '@utils/wxapi';
Page({
  data: {
    nav: [
      { name: '全部', status: '' },
      { name: '已完成', status: 'SUCCESS' },
      { name: '待付款', status: 'UNPAID' },
      { name: '已取消', status: 'CANCEL' },
    ],
    navnum: 0,
    list: [],
    odlist: [],
    page: 1,
    size: 20,
    pageTotal: 0,
  },
  onLoad() {
    this.orderList();
  },
  async orderList() {
    try {
      const { page, size, odlist, navnum, nav } = this.data;
      const { respCode, source, msg, pageTotal } = await api.orders_list({ page, size });
      if (respCode === 200) {
        const list = JSON.parse(source);
        log(list);
        const updatedOdlist = odlist.length === 0 ? list : odlist.concat(list);
        const filteredList = navnum === 0 ? updatedOdlist : this.filter(nav[navnum].status);
        this.setData({
          odlist: updatedOdlist,
          pageTotal,
          list: filteredList,
        });
      } else {
        toast(msg);
      }
    } catch (error) {
      err(error);
      throw error;
    }
  },
  navtap(e) {
    try {
      const i = e.currentTarget.dataset.index;
      if (i === 0) {
        this.setData({ navnum: i, list: this.data.odlist });
      } else {
        const status = this.data.nav[i].status;
        const list = this.filter(status);
        this.setData({ navnum: i, list });
      }
    } catch (error) {
      err(error);
      throw error;
    }
  },
  todtl(e) {
    const { id } = e.currentTarget.dataset;
    to('/user/pages/order/order?id=' + id);
  },
  filter(status) {
    const orders = this.data.odlist;
    const filteredList = orders.filter(cur => cur.status === status);
    return filteredList;
  },
  onReachBottom() {
    const { list, pageTotal, page } = this.data;
    if (list.length < pageTotal) {
      this.setData({ page: page + 1 });
      this.orderList();
    } else {
      toast('已加载全部数据');
    }
  },
});
